package com.sptpc.stu.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.sptpc.stu.common.controller.BaseController;
import com.sptpc.stu.common.response.JSONResponse;
import com.sptpc.stu.common.utils.QueryPage;
import com.sptpc.stu.controller.request.ChoiceCourseRequest;
import com.sptpc.stu.controller.request.EditStudentRequest;
import com.sptpc.stu.controller.request.NewStudentRequest;
import com.sptpc.stu.controller.request.SearchStuRequest;
import com.sptpc.stu.model.Course;
import com.sptpc.stu.model.Major;
import com.sptpc.stu.model.Student;
import com.sptpc.stu.repository.CourseRepository;
import com.sptpc.stu.repository.MajorRepository;
import com.sptpc.stu.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/stu")
public class StudentController extends BaseController {

    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private MajorRepository majorRepository;
    @Autowired
    private CourseRepository courseRepository;

    // CRUD 增删查改
    // 1、查询接口
    @GetMapping("/list")
    public JSONResponse getAllStudents(SearchStuRequest stuRequest,
                                       QueryPage queryPage) {

        Page<Student> page = null;
        if(StrUtil.isNotBlank(stuRequest.getName())) {
            String searchName = "%" + stuRequest.getName() + "%";
            if (stuRequest.getGender()==null) {
                page = studentRepository.findStudentsPageByNameLike(
                        searchName,
                        PageRequest.of(queryPage.getPage() - 1, queryPage.getLimit())
                );
            } else {
                page = studentRepository.findStudentsPageByNameLikeAndGender(
                        searchName,
                        stuRequest.getGender(),
                        PageRequest.of(queryPage.getPage() - 1, queryPage.getLimit())
                );
            }
        } else {
            if (stuRequest.getGender()!=null) {
                page = studentRepository.findStudentsPageByGender(
                        stuRequest.getGender(),
                        PageRequest.of(queryPage.getPage() - 1, queryPage.getLimit())
                );
            } else {
                page = studentRepository.findAll(
                        PageRequest.of(queryPage.getPage() - 1, queryPage.getLimit()));
            }
        }

        return JSONResponse.ofSuccess(getData(page));
    }
//
//    // 2、按学号查询接口
//    // /stu/?id='2019001'
//    // <a href='stu/?id=2'>第2页</a>
//    @GetMapping(value = "/", params = "id")
//    public Student getStudentById(@RequestParam String id) {
//        // mock
//        Student stu = new Student("2018001", "张三", LocalDate.parse("2019-09-01"), true, 10);
//        return stu;
//    }
//
//    // 3、按学号查询接口01
//    // /stu/2018001  path
//    @GetMapping("/{id}")
//    public Student getStudentByPath(
//            @PathVariable String id) {
//        // mock
//        Student stu = new Student("2018001", "张三", LocalDate.parse("2019-09-01"), true, 10);
//        return stu;
//    }
//
    // json格式传数据
    @PostMapping(value = "/add",
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public JSONResponse addNewStudent(@RequestBody NewStudentRequest stu) {
        // 学生信息写入数据库
        Student saveStudent = new Student();
        stu.setAvatar(stu.getAvatar().substring("http://localhost:8080".length()));
        BeanUtil.copyProperties(stu, saveStudent);
        Major major = majorRepository.getOne(stu.getMajorId());
        saveStudent.setMajor(major);

        studentRepository.save(saveStudent);

        return JSONResponse.ofSuccess();
    }
//
//    // form表单传数据
//    // <form action='stu/' method='get'>
//    //    <input type='text' name='id'/>
//    // </form>
//    @PostMapping(value = "/add")
//    public Student addNewStudent2(Student stu) {
//        // TODO: 学生信息写入数据库
//        // mock
//        Student savedStu = new Student("2018001", "张三", LocalDate.parse("2019-09-01"), true, 10);
//        return savedStu;
//    }
//
//    // form表单传数据
//    @PostMapping(value = "/search",
//            consumes = MediaType.APPLICATION_JSON_VALUE)
//    public Student searchStudent(@RequestBody SearchStuRequest search) {
//        // TODO: select  search -> where
//        // mock
//        Student searchStu = new Student("2018001", "张三", LocalDate.parse("2019-09-01"), true, 10);
//        return searchStu;
//    }

    // 修改学生信息
    // 等价于@RequestMapping(method = RequestMethod.PUT)
    @PutMapping(value = "/update", consumes = MediaType.APPLICATION_JSON_VALUE)
    public JSONResponse updateStudent(@RequestBody EditStudentRequest stu) {
        // 通过id将数据库中原有学生信息查询出来 stu.getId()
        Optional<Student> optional =
                studentRepository.findById(stu.getId());

        if (optional.isPresent()) {
            Student student = optional.get();
            BeanUtil.copyProperties(stu, student);

            if (stu.getMajorId()!=null) {
                Major major = majorRepository.getOne(stu.getMajorId());
                student.setMajor(major);
            }
            studentRepository.saveAndFlush(student);
            return JSONResponse.ofSuccess();
        }

        return JSONResponse.ofFail("学生id不存在");
    }

    // /stu/del/2018001  path
    @DeleteMapping("/del/{sid}")
    public JSONResponse deleteStudentByPath(
            @PathVariable String sid) {
        // 在数据库中删除对应的学生信息
        Student studentExample = Student.builder()
                .sid(sid).build();
        Example<Student> example = Example.of(studentExample);
        Optional<Student> optionalStudent = studentRepository.findOne(example);
        if (optionalStudent.isPresent()) {
            studentRepository.deleteById(optionalStudent.get().getId());
            return JSONResponse.ofSuccess();
        } else {
            return JSONResponse.ofFail("输入的学号有误，请查询后再尝试");
        }
    }

//    // /stu/del?id=2018001
//    @DeleteMapping(value = "/del", params = "id")
//    public String deleteStudentByParam(
//            @RequestParam String id) {
//        // TODO: 在数据库中删除对应的学生信息
//
//        return "删除成功";
//    }


    @PostMapping(value = "/choice", consumes = MediaType.APPLICATION_JSON_VALUE)
    public void choiceCourse(@RequestBody ChoiceCourseRequest courseRequest) {
        List<Course> coures = courseRepository.findCoursesByIdIn(courseRequest.getCourseIds());
        Student student = studentRepository.getOne(courseRequest.getSid());
        student.setCourses(coures);
        studentRepository.saveAndFlush(student);
    }

    @GetMapping(value = "/{sid}/course")
    public List<Course> getCourseByStudent(@PathVariable Long sid) {
        return studentRepository.getOne(sid).getCourses();
    }
}
